<template>
  <div class="books">
    <Loading v-if="loading" />
    <h1 v-else>{{ title }}</h1>
    <BookList :list="books" v-if="books.length" />
    <h3>{{ message }}</h3>
  </div>
</template>
<script>
import Loading from "@/components/Loading";
import BookList from "@/components/BookList";

export default {
  name: "Books",
  data() {
    return {
      loading: true,
      title: "",
      message: "",
      books: [],
    };
  },
  components: {
    Loading,
    BookList,
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.title = to.meta.title;
      let url = vm.setRequestUrl(to.fullPath);
      vm.getBooks(url);
    });
  },
  // created(){
  //   console.log(this.$route);
  //   this.title = this.$route.meta.title;
  //   let url = this.setRequestUrl(this.$route.fullPath);
  //   this.getBooks(url);
  // },
  beforeRouteUpdate(to) {
    this.books = [];
    let url = this.setRequestUrl(to.fullPath);
    this.getBooks(url);
    return true;
  },
  methods: {
    getBooks(url) {
      this.message = "";
      setTimeout(() => {
        this.axios
          .get(url)
          .then((res) => {
            this.loading = false;
            this.books = res.data;
            if (this.books.length == 0) {
              if (this.$route.name == "/category") {
                this.message = "当前分类没有图书";
              } else {
                this.message = "没有搜索到该图书";
              }
            }
          })
          .catch((err) => {
            this.message = "没有搜索到该图书";
            console.log(err);
            this.loading = false;
          });
      }, 1000);
    },
    setRequestUrl(path) {
      let url = path;
      // if(path.indexOf('/category') != -1){
      //     url ="/book"+url;
      // }
      return url;
    },
  },
};
</script>

<style>
.books h1 {
  font-size: 20px;
  font-weight: 700;
}
</style>
